package com.sangeng.filter;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.sangeng.domain.LoginUser;
import com.sangeng.domain.MockRedis;
import com.sangeng.domain.User;
import com.sangeng.mapper.MockRedisMapper;
import com.sangeng.service.MockRedisService;
import com.sangeng.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private MockRedisService mockRedisService;

    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行，没有拿到token则放行。   另外，其他地方会判断有无token
            filterChain.doFilter(request, response);
            return;
        }
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            System.out.println("doFilterInternal===>  "+e);
//            throw new ServletException("token非法");
            resolver.resolveException(request, response, null, new RuntimeException("token解析错误"));
            return;
        }
        // 从redis中获取用户信息
        String redisKey = "login:" + userid;
        String s = mockRedisService.get(redisKey);

        if (ObjectUtils.isNull(s)) {
//            throw new RuntimeException("用户未登录");
            resolver.resolveException(request, response, null, new RuntimeException("用户未登录"));
            return;
        }
        LoginUser loginUser = JSONObject.parseObject(s, LoginUser.class);
        System.out.println(loginUser);
        // 获取权限信息封装到 Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);

    }
}
